<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible.sync="dialogVisible"
    class="dialogStyleMiddle"
    :before-close="handleClose"
    :close-on-click-modal="false"
    append-to-body
  >
    <div>
      <el-form ref="formData" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡查时间段" prop="dateRange">
              <el-select v-model="formData.dateRange" style="width: 100%" clearable size="small" @change="selectDateRange">
                <el-option
                  v-for="dict in dateRangeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="date" label="巡查时间">
              <el-date-picker
                v-model="formData.date"
                style="width: 100%"
                type="daterange"
                size="small"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="dateRange"
                @change="handleChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="remark">
              <label slot="label" v-html="`备&emsp;&emsp;注`" />
              <el-input v-model="formData.remark" style="width:100%" :maxlength="500" :rows="3" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider style="margin:10px" />
      <!--搜索表单-->
      <el-form v-if="dialogVisible" ref="form" :model="filters" label-width="80px" class="dialog-form">
        <el-row>
          <el-col :span="10" class="formHeight">
            <el-form-item label="人员名称" prop="userName">
              <label slot="label">人员名称</label>
              <el-input v-model="filters.userName" placeholder="请输入人员名称" clearable size="small" @change="userNameChange" />
            </el-form-item>
          </el-col>
          <el-col :push="1" :span="5">
            <el-button v-clickForbidden icon="el-icon-search" size="small" type="primary" @click="handleQuery">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!--列表-->
      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        class="table-list"
        max-height="310"
        :row-key="getRowKeys"
        :row-style="rowClass"
        size="mini"
        @selection-change="handleSelectionChange"
        @row-click="rowChecked"
      >
        <el-table-column type="selection" width="38" :reserve-selection="true" />
        <el-table-column prop="userName" label="姓名" align="center" min-width="60" />
        <el-table-column prop="idCard" label="身份证号" align="center" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="deptName" label="所属部门" align="center" min-width="80" :show-overflow-tooltip="true" />
      </el-table>
      <!-- 分页-->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="filters.pageNum"
        :limit.sync="filters.pageSize"
        :page-sizes="[8,15,20,50,100]"
        :page-count="filters.pageCount"
        @pagination="getList"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="medium" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 引入人员列表
import { mapState } from 'vuex'
export default {
  props: {
    getPersonList: {
      type: Function,
      default: () => function() {}
    },
    dateRangeList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      title: '', // 弹框标题
      dialogVisible: false, // 弹框标识
      // 搜索框 start
      filters: { // form数据
        sysUserType: '01',
        typeFlag: '1',
        pageNum: 1,
        pageSize: 8,
        pageCount: 5,
        userName: '',
        proId: ''
      },
      rules: {
        dateRange: [{ required: true, message: '巡查时间段不能为空!', trigger: 'change' }],
        date: [{ required: true, message: '巡查开始和结束时间不能为空!', trigger: 'change' }],
        remark: [{ required: true, message: '备注不能为空!', trigger: 'blur' }]
      },
      formData: {
        dateRange: '',
        date: '',
        remark: '',
        endTime: '',
        startTime: ''
      },
      dateRangeStart: '', // 开始巡查时间范围
      dateRangeEnd: '', // 结束巡查时间范围
      // 日期选择器可选择范围
      dateRange: {
        disabledDate: this.disabledDate
      },
      /** 表格数据 start */
      total: 0, // 分页总页数
      tableData: [], // 表格数据
      multipleSelection: [], // 多选框选中数组
      selectRow: [], // 高亮数组
      getRowKeys(row) { // 分页记录功能
        return row.id
      },
      // 人员选中start
      personIds: [], // 被选中人员id数组
      personNames: [], // 被选中人员名字数组
      echoIds: [], // 用于存储分页回显的数据
      choice: '多选', // 单选,多选
      ids: [],
      echoList: []
    }
  },
  computed: {
    ...mapState({
      personType: state => state.basicInfo.personType // 人员类型
    })
  },
  methods: {
    // 巡查时间段变化
    selectDateRange(e) {
      // this.formData.dateRange = e
      this.dateRangeStart = e.split(',')[0]
      this.dateRangeEnd = e.split(',')[1]
    },
    // 控制可选择的时间
    disabledDate(time) {
      // 当前日期小于2021-07-30或者大于2021-08-31都禁止选择
      return new Date(time).getTime() < new Date(this.dateRangeStart).getTime() - 8.64e7 || new Date(time).getTime() > new Date(this.dateRangeEnd).getTime()
    },
    // 巡查时间变化
    handleChange(value) {
      if (!value) {
        this.formData.startTime = ''
        this.formData.endTime = ''
        return
      }
      this.formData.startTime = value[0]
      this.formData.endTime = value[1]
    },
    // 人员搜索
    userNameChange(e) {
      if (!e) {
        this.multipleSelection = []
        this.selectRow = []
        this.getList()
      }
    },
    // // 回显人员类型
    // setPersonalType(row) {
    //   return this.selectDictLabel(this.personType, row.personType)
    // },
    // 从父组件获取参数的方法
    handleAdd(title, checkStatus, sysUserType, proId, explorationId, echoIds, echoList) {
      this.dialogVisible = true
      this.filters = { ...this.filters, sysUserType, proId, explorationId }
      this.title = title
      this.selectRow = []
      this.handleChoice(checkStatus)
      if (echoIds instanceof Array) {
        this.echoIds = echoIds
      } else if (echoIds != null && echoIds !== '') {
        this.echoIds = echoIds.split(',')
      } else {
        this.echoIds = null
      }
      this.echoList = echoList
      // 用于存储被选中的人员id数组
      this.personIds = []
      this.personNames = []
      this.getList()
    },
    // 表格start
    // 获取人员列表
    async getList() {
      if (this.multipleSelection.length > 0) {
        this.echoIds = this.multipleSelection.map(item => {
          return item.userId
        })
      }
      const { data: { rows, total }} = await this.getPersonList(this.filters)
      this.tableData = rows
      this.total = total
      this.$nextTick(() => {
        this.rowMultipleChecked()
      })
    },
    /** 用于数据回显 echoIds 用于单个回显 */
    rowMultipleChecked() {
      if (this.echoIds != null) {
        this.tableData.forEach((item, i) => {
          this.echoIds.forEach((multItem, j) => {
            if (this.tableData[i].personId === this.echoIds[j]) {
              this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true) // 这步操作是让  页面显示选中的数据
            }
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
      this.$refs.multipleTable.clearSelection()
      this.emptyForm()
    },
    // 搜索方法
    handleQuery() {
      this.filters.pageNum = 1
      this.getList()
    },
    emptyForm() {
      this.formData.dateRange = ''
      this.resetForm('form')
      this.resetForm('formData')
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.emptyForm()
      this.handleQuery()
      this.echoIds = null
    },
    /** 清空按钮操作 */
    resetEmpty() {
      this.emptyForm()
      this.handleQuery()
    },
    // 控制表格选框多选单选
    handleChoice(checkStatus) {
      if (checkStatus === '0') {
        this.choice = '单选'
      } else {
        this.choice = '多选'
      }
    },
    // 多选框选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      // 单选
      if (this.choice === '单选') {
        if (val.length > 1) {
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.toggleRowSelection(val.pop())
        }
      }
      // 高亮
      this.selectRow = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      this.checkIds()
    },
    // 高亮样式
    rowClass({
      row,
      rowIndex
    }) {
      if (this.selectRow.includes(rowIndex)) {
        return {
          'background-color': 'rgba(185,221,249,.75)'
        }
      }
    },
    // 获取选中的行数并且把值返回到父节点（roleDataScopeDet）
    checkIds() {
      this.personIds = this.multipleSelection.map(item => {
        return item.personId
      })
      this.personNames = this.multipleSelection.map(item => {
        return item.userName
      })
    },
    // 点击行时,选框选中
    rowChecked(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 确定按钮
    submitForm() {
      this.$refs.formData.validate(vaild => {
        if (vaild) {
          if (!this.multipleSelection.length) {
            this.msgWarning('请选择人员')
            return
          }
          // 调用向父组件传值的方法
          this.checkIds()
          this.$emit('fatherMethod', this.personIds, this.multipleSelection, this.personNames, this.formData)
        }
      })
    }
  }
}

</script>

<style>
</style>
